//功能树
angular.module('app').component('mFunTree', {
    templateUrl: getTemplateUrl('matrix/component/tpl/mFunTree.html'),
    bindings: {
        hideTree: '@',
        reqId: '@',
        withChildren: '@',
        onNodeSelect: '&',
        relationSelect: '&',
        contactSelect: '&',
        treeOperation: "<",
        showRelationBtn: "<",
        editBtnStatus: "<",
        onChangeText: "@",
        inputFilter: "=",
        searchNextItem: "&",
        treeArray: "=",
        selectedOption: "=",
        isDisabled: "<",
        treeStatus: "@",
        getSys    : '&'
    },
    controller: function ($scope, $stateParams, $element, $http, $attrs, $modal, $timeout, $rootScope, lodash) {
        var ctrl = this;
        ctrl.my_data = [];              //tree要显示的数据
        ctrl.my_tree = {};
        ctrl.reqList = [],              //reqId下已关联的feature列表
        ctrl.selectedBranch = null;     //当前选中的分支数据
        ctrl.treeType       = "relate";
        ctrl.sltSysItem     = lodash.first(config_flow_legend_sys),
        ctrl.selectValue    = lodash.first(config_flow_legend_sys).crtname;    //系统选择框默认值
        ctrl.showAddMenu    = true,
        ctrl.showDeleteMenu = true;
        ctrl.showAddPage    = true,
        ctrl.showDeletePage = true;
        ctrl.showAddFeature = true;
        ctrl.showEditFeature= true;
        ctrl.showRelateBtn  = true;
        ctrl.showDeleteBtn  = true;
        ctrl.reqNegative    = false;
        ctrl.jumpToFeatureId= null;     //跳转到对应的featureId节点上
        ctrl.isFlowTree     = ctrl.treeStatus == "flow" ? true : false;

        if(ctrl.treeOperation){
            ctrl.treeType = "node";
        } else {
            ctrl.treeOperation = false;
        }
        ctrl.filterText = {
            "Keyword"     : "",
            "searchCount" : 0
        };
        ctrl.sysData = config_flow_legend_sys;

        //初始化
        ctrl.treeStatus == "flow" ? getBusinessTree() : getFeatures();

        //if($stateParams.reqId) {
            getFeaturesByReqId();
        //}
        ctrl.reqNegative = $stateParams.reqId == "-1" ? true : false ;

        $scope.$on('reloadGetFeatures', function(event, data){
            getFeatures();
        })

        //切换系统
        ctrl.selectChange = function(sys) {
            if(sys) {
                ctrl.sltSysItem = lodash.findWhere(config_flow_legend_sys, {"key": sys});
            }
            ctrl.showAddMenu    = true,
            ctrl.showDeleteMenu = true;
            ctrl.showAddPage    = true,
            ctrl.showDeletePage = true;
            ctrl.showAddFeature = true;
            ctrl.showEditFeature= true;
            ctrl.showRelateBtn  = true;
            ctrl.showDeleteBtn  = true;
            ctrl.selectValue = ctrl.sltSysItem.crtname;
            getFeatures(ctrl.sltSysItem.crtname);
        };

        //查询feature树（点击下一项）
        ctrl.searchNextItem = function () {
            ctrl.filterText.searchCount++;
        };

        //获取feature数据
        function getFeatures(sys) {
            var url = matrix_product_url + "/feature/getFeatureBaseTree?featureSys=" + (sys == undefined ? "tom" : sys);
            $http.get(url).success(function(result) {
                if(result.code == "0") {
                    ctrl.my_data = result.data ? result.data : [];
                } else {
                    $rootScope.showMessage("error", "失败", result.desc);
                }
            });
        };

        //获取业务树数据
        function getBusinessTree() {
            var url = matrix_product_url +"/productLine/getProductLineTree";
            $http.get(url).success(function(result) {
                if(result.code == "0") {
                    if(result.data) {
                        ctrl.my_data = [result.data];
                    } else {
                        $rootScope.toasterErrorInfo("获取业务树数据失败！");
                    }
                } else {
                    $rootScope.toasterErrorInfo(result.desc);
                }
            });
        };

        //根据reqId获取已关联的feature列表
        function getFeaturesByReqId() {
            var url = matrix_product_url + "/feature/getAllFeatureForReq?reqId=" + ($stateParams.reqId ? $stateParams.reqId : ctrl.reqId);
            $http.get(url).success(function(result) {
                if(result.code == "0") {
                    ctrl.reqList = result.data;
                } else {
                    $rootScope.showMessage("error", "失败", result.desc);
                }
            });
        };

        //声明方法(editTree调用)
        $scope.$on("getFeaturesByReqId", function(event, data) {
            getFeaturesByReqId();
            if(ctrl.selectedBranch) {
                ctrl.selectedBranch.status = $stateParams.reqId == "-1" ? "ONLINE" : "UPDATE";
            }
        });

        //点击列表数据，定位到该数据的page节点
        ctrl.goTo = function(pageId, featureId, featureSys, sltSys) {
            if(pageId != undefined){
                if(featureId != undefined){
                    if(sltSys.crtname != featureSys) {
                        ctrl.selectChange(featureSys);
                        $timeout(function() {
                            getReqListByPageId(pageId);
                            ctrl.jumpToFeatureId = featureId;
                            // ctrl.my_tree.set_select_branch_by_id(featureId);
                        }, 500);
                    } else {
                        ctrl.jumpToFeatureId = featureId;
                        // ctrl.my_tree.set_select_branch_by_id(featureId);
                    }
                }
                ctrl.my_tree.set_select_branch_by_id(pageId);
            }

        };

        //选中树分支时，获取分支数据
        ctrl.my_tree_handler = function(branch) {
            console.log('--------查看当前点击的分支数据------------');
            console.log(branch);
            ctrl.selectedBranch = ctrl.my_tree.get_selected_branch();
            ctrl.onNodeSelect({
                info: branch
            });
            ctrl.isFlowTree ? initBusiness(branch) : initFeature(branch);
        };

        //设置feature的初始化信息
        function initFeature(branch) {
            if(branch.nodeType == "page") {
                ctrl.showDeletePage  = $stateParams.reqId == "-1" ? false : true;   //删除page
                ctrl.showAddPage     = true;   //添加page
                ctrl.showEditFeature = true;
                ctrl.showAddMenu     = true;  //添加menu
                ctrl.showDeleteMenu  = true;  //删除menu
                ctrl.showAddFeature  = false;
                ctrl.showRelateBtn   = true;
                getReqListByPageId(branch.id);
            }
            if(branch.nodeType == "menu") {
                ctrl.showEditFeature = true;
                ctrl.showAddMenu     = false;  //添加menu
                ctrl.showDeleteMenu  = $stateParams.reqId == "-1" ? false : true;   //删除menu
                ctrl.showAddPage     = branch.parentId == "0" ? true : false;
                ctrl.showAddFeature  = true;
                ctrl.showRelateBtn   = true;
            }
            if(branch.nodeType == undefined) {
                //当前为req节点
                ctrl.showAddFeature  = true;
                ctrl.showAddMenu     = true;
                ctrl.showDeleteMenu  = true;
                ctrl.showAddPage     = true;
                ctrl.showDeletePage  = true;
                ctrl.showEditFeature = branch.reqId == "-1" ? true : ($stateParams.reqId == "-1" ? true : false);
                ctrl.showDeleteBtn   = $stateParams.reqId == "-1" ? (branch.type == "PROTOTYPE" ? true : false) : true ;
                ctrl.showRelateBtn   = branch.reqId == "-1" ? true : (branch.reqId == $stateParams.reqId ? false : true);
                if($stateParams.reqId != "-1") {
                    for(var i = 0; i < ctrl.reqList.length; i++) {
                        if(ctrl.reqList[i].id == branch.id) {
                            ctrl.showEditFeature = true;
                            ctrl.showRelateBtn = false;
                            break;
                        } else {
                            ctrl.showEditFeature = false;
                            ctrl.showRelateBtn = true;
                        }
                    }
                    if(ctrl.reqList.length == 0) {
                        ctrl.showEditFeature = false;
                    }
                }
                if(ctrl.reqList.length == 0) {
                    ctrl.showEditFeature = false;
                }
            } else {
                //当前为menu,page节点
                if(!branch.metaData) {
                    console.log("节点数据metaData未定义！");
                    return false;
                }
                var level = parseInt(branch.metaData.level) + 1;
                if(branch.nodeType == "page" && !branch.metaData.level) {
                    level = 5;
                }
            }
        };

        //设置business的初始化信息
        function initBusiness(branch) {
            // var level;
            // if(angular.isString(branch.level)) {
            //     level = parseInt(branch.level) + 1;
            // } else {
            //     level = branch.level;
            // }
            // if(level == 4) {
            //     getFlowListByBusinessId(branch.id);
            // }
            // ctrl.showAddPage     = true;
            // ctrl.showDeletePage  = true;
            // if($stateParams.reqId == "-1") {
            //     ctrl.showAddMenu     = level <= 3 ? false : true;
            //     ctrl.showDeleteMenu  = (level == 2 || level == 3 || level == 4) ? false : true;
            //     ctrl.showAddFeature  = level == 4 ? false : true;
            //     ctrl.showEditFeature = true;
            //     ctrl.showDeleteBtn   = branch.level == undefined ? false : true;
            //     ctrl.showRelateBtn   = true;
            // } else {
            //     ctrl.showAddMenu     = true;
            //     ctrl.showDeleteMenu  = true;
            //     ctrl.showEditFeature = true;

            // }

        };

        //根据businessId查询business列表
        function getFlowListByBusinessId(businessId) {
            if(!businessId) {
                $rootScope.toasterErrorInfo("businessId未定义！");
                return false;
            }
            var url = matrix_product_url +"/flow/getBusinessFlows?businessId="+ businessId;
            $http.get(url).success(function(result) {
                if(result.code == "0") {
                    var branch = ctrl.my_tree.get_branch_by_id(businessId);
                    branch.children = result.data;
                    if(result.data != null && result.data.length > 0){
                        ctrl.my_tree.expand_branch(branch);
                    }
                } else {
                    $rootScope.toasterErrorInfo(result.desc);
                }
            });
        };

        //根据pageId查询req列表
        function getReqListByPageId(pageId) {
            if(!pageId) {
                $rootScope.showMessage("error", "失败", "pageId未定义！");
                return false;
            }
            var url = matrix_product_url + "/feature/getPageFeatures?pageId=" + pageId;
            $http.get(url).success(function(result) {
                if(result.code == "0") {
                    var branch = ctrl.my_tree.get_branch_by_id(pageId);
                    branch.children = result.data;
                    if(result.data != null && result.data.length > 0){
                        ctrl.my_tree.expand_branch(branch);
                    }
                    if(ctrl.jumpToFeatureId != null){
                        ctrl.my_tree.set_select_branch_by_id(ctrl.jumpToFeatureId);
                        ctrl.jumpToFeatureId = null;
                    }
                } else {
                    $rootScope.showMessage("error", "失败", result.desc);
                }
            });
        };

        //点击新增按钮，打开modal---menu
        ctrl.addMenuBranch = function() {
            menuModal(ctrl.selectedBranch, $stateParams.reqId, ctrl.selectValue, true, ctrl.isFlowTree);
        };

        function menuModal(selectedBranch, reqId, sys, status, isFlowTree) {
            var modalInstance = $modal.open({
                animation: true,
                templateUrl: getTemplateUrl("matrix/component/tpl/menuModal.html"),
                controller: "addMenuModalCtrl",
                keyboard: true,
                backdrop: true,
                resolve: {
                    branch: function () {
                        return selectedBranch;
                    },
                    reqId: function() {
                        return reqId;
                    },
                    sysName: function() {
                        return sys;
                    },
                    status: function() {
                        return status;
                    },
                    isFlowTree: function() {
                        return isFlowTree;
                    }
                }
            });

            //点击modal新增后，把值传过来
            modalInstance.result.then(function(menu) {
                ctrl.isFlowTree ? createFlowMenu(menu) : setRouteId(menu, selectedBranch);
            }, function(reason) {
                cancelModal(reason);
            });
        };

        //创建flow节点
        function createFlowMenu(data) {
            var url = matrix_product_url +"/productLine/saveProductLine";
            var postParams = {
                "name"     : data.name,
                "level"    : data.menuStatus ? ctrl.selectedBranch.level : ctrl.selectedBranch.level-1,
                "parentId" : data.menuStatus ? ctrl.selectedBranch.id : ctrl.selectedBranch.parentId,
                "isDel"    : "1",
            };
            data.menuStatus ? postParams : postParams.id = ctrl.selectedBranch.id;
            $http({
                method   : "post",
                url      : url,
                data     : JSON.stringify(postParams),
                headers : {"Content-Type": "application/json"}
            }).success(function(result) {
                if(result.code == "0") {
                    if(data.menuStatus) {   //新增
                        if(!result.data) {
                            $rootScope.toasterErrorInfo("创建流程，返回数据错误！");
                        }
                        var newNodeData = {
                            "id"       : result.data,
                            "name"     : postParams.name,
                            "level"    : postParams.level+1,
                            "parentId" : postParams.parentId,
                            "isDel"    : postParams.isDel,
                            "children" : [],
                        };
                        ctrl.selectedBranch.children.push(newNodeData);
                    } else { //修改
                        ctrl.selectedBranch.name = data.name;
                    }
                    $rootScope.toasterSuccessInfo(data.menuStatus ? "创建成功！" : "修改成功！" );
                } else {
                    $rootScope.toasterErrorInfo(result.desc);
                }
            });
        };

        function setRouteId(data, selectedBranch) {
            //set routeId
            var path = "";
            var crtId = ctrl.selectedBranch.id;
            if(ctrl.selectedBranch.level == 1) {
                path = ctrl.selectedBranch.metaData.menu_data.path ? "/" + ctrl.selectedBranch.metaData.menu_data.path : "";
            } else if(ctrl.selectedBranch.level == 2) {
                var fatherBranch = ctrl.my_tree.select_parent_branch();
                path = "/" + fatherBranch.metaData.menu_data.path + "/" + ctrl.selectedBranch.metaData.menu_data.path;
            } else if(ctrl.selectedBranch.level == 3) {
                var fatherBranch = ctrl.my_tree.select_parent_branch();
                var grandFatherBranch = ctrl.my_tree.select_parent_branch();
                path = "/" + grandFatherBranch.metaData.menu_data.path + "/" + fatherBranch.metaData.menu_data.path + "/" + ctrl.selectedBranch.metaData.menu_data.path;
            }
            ctrl.my_tree.set_select_branch_by_id(crtId);
            createMenuModal(data, path, selectedBranch);
        };

        //modal按钮新增---menu
        function createMenuModal(menu, path, selectedBranch) {
            var randomId = 'MENU' + new Date().getTime();
            //var level = menu.menuStatus ? parseInt(ctrl.selectedBranch.level) : parseInt(ctrl.selectedBranch.level)-1;
            if(ctrl.selectedBranch.parentId == 0) {
                var level = 1;
            } else {
                var level = menu.menuStatus ? parseInt(ctrl.selectedBranch.metaData.level)+1 : parseInt(ctrl.selectedBranch.metaData.level);
            }
            var postParams = {
                "id"        : menu.menuStatus ? "" : ctrl.selectedBranch.id,
                "is_del"    : menu.menuStatus ? "" : null,
                "level"     : level+"",
                "sys"       : angular.uppercase(ctrl.selectValue),
                "status"    : menu.menuStatus ? "ADD" : "UPDATE",
                "req_id"    : "-1",
                "parent_id" : menu.menuStatus ? ctrl.selectedBranch.id : ctrl.selectedBranch.parentId,
                "menu_name" : menu.name,
                "classes"   : [],
                "menu_data" : {
                    "name"    : menu.name,
                    "path"    : menu.path || "",
                    "routeId" : (path ? path + "/" : "") + (menu.path || "")
                }
            };
            var url = matrix_product_url + "/menu/save";
            $http({
                method  : "post",
                url     : url,
                data    : JSON.stringify(postParams),
                headers : {"Content-Type": "application/json"}
            }).success(function(result) {
                if(result.code == "0") {
                    if(menu.menuStatus) {
                        if(selectedBranch.children == null) {
                            selectedBranch.children = [];
                        }
                        result.data.name     = menu.name;
                        result.data.status   = "ONLINE";
                        result.data.nodeType = "menu";
                        result.data.level    = parseInt(result.data.level)+1;
                        var crtLevel         = (parseInt(result.data.level)-1)+"";
                        result.data.metaData = {
                            "id"        : result.data.id,
                            "level"     : crtLevel,
                            "sys"       : angular.uppercase(ctrl.selectValue),
                            "status"    : "ONLINE",
                            "menu_name" : menu.name,
                            "classes"   : [],
                            "menu_data" : {
                                "id"      : result.data.id,
                                "name"    : menu.name,
                                "path"    : menu.path || "",
                                "routeId" : (path ? path + "/" : "") + (menu.path || "")
                            }
                        };
                        selectedBranch.children.push(result.data);
                    } else {
                        selectedBranch.name = menu.name;
                    }
                    $rootScope.showMessage("success", "成功", (menu.menuStatus ? "创建成功！" : "修改成功！"));
                } else {
                    $rootScope.showMessage("error", "失败", result.desc);
                }
            });
        };

        //修改--menu
        ctrl.updateMenuBranch = function() {
            var confirmParams = {
                "titleData" : "提示",
                "bodyData"  : "确定要修改【"+ ctrl.selectedBranch.name +"】节点吗？"
            };
            $rootScope.confirmWindow(confirmParams, function (data) {
                if (data) {
                    menuModal(ctrl.selectedBranch, $stateParams.reqId, ctrl.selectValue, false, ctrl.isFlowTree);
                }
            });
        };

        //删除--menu
        ctrl.deleteMenuBranch = function() {
            var confirmParams = {
                "titleData" : "提示",
                "bodyData"  : "确定要删除【"+ ctrl.selectedBranch.name +"】节点吗？"
            };
            $rootScope.confirmWindow(confirmParams, function (data) {
                if (data) {
                    ctrl.isFlowTree ? deleteBusiness() : deleteFeatureMenu();
                }
            });
        };

        //删除business节点
        function deleteBusiness() {
            if(!ctrl.selectedBranch.id) {
                $rootScope.toasterErrorInfo("删除失败，节点id未定义！");
                return false;
            }
            var url = matrix_product_url +"/productLine/deleteProductLine?businessId="+ ctrl.selectedBranch.id;
            $http.get(url).success(function(result) {
                if(result.code == "0") {
                    var branchArray = ctrl.my_tree.get_parent_branch(ctrl.selectedBranch).children;
                    for(var i = branchArray.length-1; i >= 0; i--){
                        if(branchArray[i].id == ctrl.selectedBranch.id) branchArray.splice(i,1);
                    }
                    $rootScope.toasterSuccessInfo("删除成功！");
                } else {
                    $rootScope.toasterErrorInfo(result.desc);
                }
            });
        };

        //删除feature-menu
        function deleteFeatureMenu() {
            var deleteId = ctrl.selectedBranch.id;
            if(!deleteId) {
                $rootScope.showMessage("error", "失败", "menuId未定义！");
            }
            var postParams = {
                "id" : deleteId,
                "status" : "DELETE"
            };
            var url = matrix_product_url + "/menu/save";
            $http({
                method  : "post",
                url     : url,
                data    : JSON.stringify(postParams),
                headers : {"Content-Type": "application/json"}
            }).success(function(result) {
                if(result.code == "0") {
                    var branchArray = ctrl.my_tree.get_parent_branch(ctrl.selectedBranch).children;
                    var id = deleteId;
                    for(var i = branchArray.length-1; i >= 0; i--){
                        if(branchArray[i].id == id) branchArray.splice(i,1);
                    }
                    ctrl.showAddMenu    = true,
                    ctrl.showDeleteMenu = true;
                    ctrl.showAddPage    = true,
                    getFeaturesByReqId();
                    $rootScope.showMessage("success", "成功", "menu节点删除成功！");
                } else {
                    $rootScope.showMessage("error", "失败", result.desc);
                }
            });
        };

        //点击新增按钮，打开modal---page
        ctrl.addPageBranch = function() {
            pageModal(ctrl.selectedBranch, $stateParams.reqId, true);
        };

        function pageModal(selectedBranch, reqId, status) {
            var modalInstance = $modal.open({
                animation: true,
                templateUrl: getTemplateUrl("matrix/component/tpl/pageModal.html"),
                controller: "addPageModalCtrl",
                keyboard: true,
                backdrop: true,
                resolve: {
                    branch: function () {
                        return selectedBranch;
                    },
                    reqId: function() {
                        return reqId;
                    },
                    status: function() {
                        return status;
                    }
                }
            });

            //点击modal新增后，把值传过来
            modalInstance.result.then(function(page) {
                createPageModal(page);
            }, function(reason) {
                cancelModal(reason);
            });
        };

        //modal按钮新增----page
        function createPageModal(page) {
            var pageId     = page.pageStatus ? "" : ctrl.selectedBranch.id;
            var pageMenuId = page.pageStatus ? ctrl.selectedBranch.metaData.id : ctrl.selectedBranch.metaData.menuId;
            var routeId    = page.pageStatus ? ctrl.selectedBranch.metaData.menu_data.routeId : ctrl.selectedBranch.metaData.menuPath;
            var postParams = {
                "id"       : pageId,
                "title"    : page.name,
                "fileName" : "",
                "models"   : "",
                "menuId"   : pageMenuId,
                "menuPath" : routeId,
            };
            var url = matrix_product_url + "/page/savePage";
            $http({
                method  : "post",
                url     : url,
                data    : JSON.stringify(postParams),
                headers : {"Content-Type": "application/json"}
            }).success(function(result) {
                if(result.code == "0") {
                    if(page.pageStatus) {
                        if(ctrl.selectedBranch.children == null) {
                            ctrl.selectedBranch.children = [];
                        }
                        result.data.name     = page.name;
                        result.data.level    = 5;
                        result.data.nodeType = "page";
                        result.data.metaData = {
                            "menuPath" : result.data.menuPath,
                            "fileName" : result.data.title,
                            "menuId"   : result.data.menuId,
                            "title"    : result.data.title
                        };
                        if(result.data.children.length) {
                            delete result.data.children;
                        }
                        ctrl.selectedBranch.children.push(result.data);
                    } else {
                        ctrl.selectedBranch.name = page.name;
                    }
                    $rootScope.showMessage("success", "成功", (page.pageStatus ? "创建成功！" : "修改成功！"));
                } else {
                    $rootScope.showMessage("error", "失败", result.desc);
                }
            });
        };

        //修改--page
        ctrl.updatePageBranch = function() {
            var confirmParams = {
                "titleData" : "提示",
                "bodyData"  : "确定要修改PAGE【"+ ctrl.selectedBranch.name +"】节点吗？"
            };
            $rootScope.confirmWindow(confirmParams, function (data) {
                if (data) {
                    pageModal(ctrl.selectedBranch, $stateParams.reqId, false);
                }
            });
        };

        //删除--page
        ctrl.deletePageBranch = function() {
            var confirmParams = {
                "titleData" : "提示",
                "bodyData"  : "确定要删除PAGE【"+ ctrl.selectedBranch.name +"】节点吗？"
            };
            $rootScope.confirmWindow(confirmParams, function (data) {
                if (data) {
                    var deleteId = ctrl.selectedBranch.id;
                    if(!deleteId) {
                        $rootScope.showMessage("error", "失败", "pageId未定义！");
                    }
                    var url = matrix_product_url + "/page/deletePage?pageId=" + deleteId;
                    $http.get(url).success(function(result) {
                        if(result.code == "0") {
                            var branchArray = ctrl.my_tree.get_parent_branch(ctrl.selectedBranch).children;
                            var id = deleteId;
                            for(var i = branchArray.length-1; i >= 0; i--){
                                if(branchArray[i].id == id) branchArray.splice(i,1);
                            }
                            ctrl.showDeletePage = true;
                            ctrl.showAddFeature = true;
                            getFeaturesByReqId();
                            $rootScope.showMessage("success", "成功", "page节点删除成功！");
                        } else {
                            $rootScope.showMessage("error", "失败", result.desc);
                        }
                    });
                }
            });
        };

        //点击新增按钮，打开modal---feature
        ctrl.addFeatureBranch = function() {
            ctrl.isFlowTree ? flowModal(ctrl.selectedBranch, ctrl.selectValue, $stateParams.reqId) : featureModal(ctrl.selectedBranch, ctrl.selectValue, $stateParams.reqId);
        };

        //添加flow
        function flowModal(selectedBranch, sys, reqId) {
            var modalInstance = $modal.open({
                animation: true,
                templateUrl: getTemplateUrl("matrix/component/tpl/addFlow.html"),
                controller: "addFlowCtrl",
                keyboard: true,
                backdrop: true,
                resolve: {
                    branch: function () {
                        return selectedBranch;
                    },
                    sysName: function() {
                        return sys;
                    },
                    reqId: function() {
                        return reqId;
                    }
                }
            });

            //点击modal新增后，把feature值传过来
            modalInstance.result.then(function(flow) {
                createFlow(flow);
            }, function(reason) {
                cancelModal(reason);
            });
        };

        //新增flow数据
        function createFlow(flow) {
            var attrs = {"path": flow.path, "pathId": flow.pathId, "desc": flow.desc};
            var postParams = {
                "reqId"      : "-1",
                "name"       : flow.name,
                "businessId" : ctrl.selectedBranch.id,
                "status"     : "ONLINE",
                "attrs"      : attrs
            };
            var url = matrix_product_url +"/flow/saveFlow";
            $http({
                method   : "post",
                url      : url,
                data     : JSON.stringify(postParams),
                headers : {"Content-Type": "application/json"}
            }).success(function(result) {
                if(result.code == "0") {
                    if(!result.data) {
                        $rootScope.toasterErrorInfo("新增flow时返回数据错误！");
                    }
                    postParams.id = result.data;
                    ctrl.selectedBranch.children.push(postParams);
                    $rootScope.toasterSuccessInfo("创建成功！");
                } else {
                    $rootScope.toasterErrorInfo(result.desc);
                }
            });

        };

        function featureModal(selectedBranch, sys, reqId) {
            var modalInstance = $modal.open({
                animation: true,
                templateUrl: getTemplateUrl("matrix/component/tpl/featureModal.html"),
                controller: "addFeatureModalCtrl",
                keyboard: true,
                backdrop: true,
                resolve: {
                    branch: function () {
                        return selectedBranch;
                    },
                    sysName: function() {
                        return sys;
                    },
                    reqId: function() {
                        return reqId;
                    }
                }
            });

            //点击modal新增后，把feature值传过来
            modalInstance.result.then(function(feature) {
                createFeatureModal(feature);
            }, function(reason) {
                cancelModal(reason);
            });
        };

        //modal新增数据---feature
        function createFeatureModal(feature) {
            if(feature.radioStatus == "true") {
                createFeature(feature);
            } else {
                relateFeature(feature);
            }
        };

        //创建功能点（新增）
        function createFeature(feature) {
            var roleString = "";
            angular.forEach(feature.role, function(role, num) {
                roleString += role.key + ",";
            });
            var postParams = {
                "sys"            : ctrl.selectValue,
                "path"           : ctrl.selectedBranch.metaData.menuPath + "/" + ctrl.selectedBranch.metaData.title,
                "reqId"          : $stateParams.reqId,
                "pageId"         : ctrl.selectedBranch.id,
                "originalPageId" : ctrl.selectedBranch.id,
                "featureName"    : feature.name,
                "attr"           : {
                    "feature_name" : feature.name,
                    "feature_role" : roleString,
                    "feature_desc" : feature.desc,
                    "feature_in"   : feature.in,
                    "feature_out"  : feature.out,
                    "feature_logic": feature.logic
                }
            };

            var url = matrix_product_url + "/feature/createFeature";
            $http({
                method  : "post",
                url     : url,
                data    : JSON.stringify(postParams),
                headers : {"Content-Type": "application/json"}
            }).success(function(result) {
                if(result.code == "0") {
                    var addFeatureObj = {
                        "id"           : result.data,
                        "pageId"       : null,
                        "reqId"        : postParams.reqId,
                        "attrConfigId" : "",
                        "path"         : postParams.path,
                        "featureName"  : postParams.featureName,
                        "sys"          : postParams.sys,
                        "status"       : $stateParams.reqId == "-1" ? "ONLINE" : "ADD",
                        "attr"         : null
                    };
                    if(ctrl.selectedBranch.children == null) {
                        ctrl.selectedBranch.children = [];
                    }
                    ctrl.selectedBranch.children.push(addFeatureObj);
                    getFeaturesByReqId();
                    $rootScope.showMessage("success", "成功", "创建成功！");
                } else {
                    $rootScope.showMessage("error", "失败", result.desc);
                }
            })
        };

        //创建功能点（关联指定pageId）
        function relateFeature(feature) {
            if(!$stateParams.reqId) {
                $rootScope.showMessage("error", "失败", "reqId未定义！");
                return false;
            }
            if(!feature.id) {
                $rootScope.showMessage("error", "失败", "featureId未定义！");
                return false;
            }
            if(!ctrl.selectedBranch.id) {
                $rootScope.showMessage("error", "失败", "pageId未定义！");
                return false;
            }
            var url = matrix_product_url + "/feature/relateToPage?reqId=" + $stateParams.reqId + "&featureId=" + feature.id + "&pageId=" + ctrl.selectedBranch.id;
            $http.get(url).success(function(result) {
                if(result.code == "0") {
                    $rootScope.showMessage("success", "成功", "创建成功！");
                    getFeaturesByReqId();
                    getReqListByPageId(ctrl.selectedBranch.id);
                } else {
                    $rootScope.showMessage("error", "失败", result.desc);
                }
            });
        };

        //modal取消
        function cancelModal() {
            console.log("cancelModal");
        };

        //修改节点(调用editTree.js中的方法)
        ctrl.updatePanel = function() {
            var info = {};
            info.titleData = "提示";
            info.bodyData = "确定要修改吗？";
            $rootScope.confirmWindow(info, function (data) {
                if (data) {
                    $scope.$emit('updateFeature', '');
                    getFeaturesByReqId();
                    ctrl.showEditFeature = true;
                    ctrl.showRelateBtn = false;
                }
            });
        };

        //删除节点(直接物理删除)    
        ctrl.deleteBranch = function() {
            var info = {};
            var label = ctrl.isFlowTree ? ctrl.selectedBranch.name : ctrl.selectedBranch.featureName;
            info.titleData = "提示";
            info.bodyData = "确定要删除节点【"+ label +"】吗？";
            $rootScope.confirmWindow(info, function (data) {
                if (data) {
                    ctrl.isFlowTree ? deleteByBusinessId() : deleteByFeatureId();
                }
            });
        };

        //删除business
        function deleteByBusinessId() {
            var url = matrix_product_url +"/flow/deleteFlow?flowId="+ ctrl.selectedBranch.id;
            $http.get(url).success(function(result) {
                if(result.code == "0") {
                    getFlowListByBusinessId(ctrl.selectedBranch.businessId);
                    $rootScope.toasterSuccessInfo("删除成功！");
                } else {
                    $rootScope.toasterErrorInfo(result.desc);
                }
            });
        };

        //删除feature
        function deleteByFeatureId() {
            var url = matrix_product_url + "/feature/deleteFeature?featureId=" + ctrl.selectedBranch.id;
            $http.get(url).success(function(result) {
                if(result.code == "0") {
                    $rootScope.showMessage("success", "成功", "删除成功！");
                    getFeaturesByReqId();
                    getReqListByPageId(ctrl.selectedBranch.pageId);
                } else {
                    $rootScope.showMessage("error", "失败", result.desc);
                }
            });
        };

        //解除关联（修改数据状态，解除关联，重置数据）
        ctrl.disassociation = function() {
            var info = {};
            info.titleData = "提示";
            info.bodyData = "确定要重置【" + ctrl.selectedBranch.featureName + "】的节点吗？";
            $rootScope.confirmWindow(info, function (data) {
                if (data) {
                    var url = matrix_product_url + "/feature/dissociateRelation?reqId=" + $stateParams.reqId + "&featureId=" + ctrl.selectedBranch.id;
                    $http.get(url).success(function(result) {
                        if(result.code == "0") {
                            var pageId = ctrl.selectedBranch.pageId;
                            var childList = ctrl.my_tree.select_parent_branch().children;
                            lodash.remove(childList, function(child) {
                                return child.id == ctrl.selectedBranch.id;
                            });
                            ctrl.showRelateBtn = true;
                            $rootScope.showMessage("success", "成功", "重置成功！");
                            getFeaturesByReqId();
                            ctrl.goTo(pageId);
                        } else {
                            $rootScope.showMessage("error", "失败", result.desc);
                        }
                    });
                }
            });
        };

        //获取功能点系统简写
        $scope.getFeatureSysSimple = function (sys) {
            if("SELLERPORTAL" == sys){
                return "OPC"
            }else{
                return sys;
            }
        }

    }//end controller
});

app.controller("addMenuModalCtrl", ["$scope", "$rootScope", "$modalInstance", "$http", "branch", "reqId", 'sysName', 'status', 'isFlowTree', function($scope, $rootScope, $modalInstance, $http, branch, reqId, sysName, status, isFlowTree) {
    $scope.isFlowTree = isFlowTree;
    $scope.menu = {
        name       : "",
        path       : "",
        menuStatus : status
    };

    $scope.createClick = function() {
        if(isFlowTree) {
            delete $scope.menu.path;
        } else {
            if(!status) {
                $scope.menu.path = branch.metaData.menu_data.path;
            }
        }
        $modalInstance.close($scope.menu);
    };

    $scope.cancelClick = function() {
        $modalInstance.dismiss("cancel");
    };
}]);

app.controller("addPageModalCtrl", ["$scope", "$rootScope", "$modalInstance", "$http", "branch", "reqId", "status", function($scope, $rootScope, $modalInstance, $http, branch, reqId, status) {
    $scope.page = {
        name       : "",
        pageStatus : status
    };

    $scope.createClick = function() {
        $modalInstance.close($scope.page);
    };

    $scope.cancelClick = function() {
        $modalInstance.dismiss("cancel");
    };
}]);

app.controller("addFeatureModalCtrl", ["$scope", "$rootScope", "$modalInstance", "$http", "branch", "sysName", "reqId", function($scope, $rootScope, $modalInstance, $http, branch, sysName, reqId) {
    $scope.info = {
        roleList       : [],      //全部角色集
        selectRoleList : [],      //已选择角色集
        radioStatus    : "true",  //单选按钮状态
        featureList    : [],      //全部feature集
        selectValue    : "",
        createBtnStatus: true
    };
    $scope.feature = {
        name : "",
        role : [],
        desc : "",       //功能描述
        in   : "",
        out  : "",
        logic: ""        //业务逻辑
    };
    getRoleList();

    //获取角色集列表
    function getRoleList() {
        var url = sys_config_url + "/select/get?type=FEATURE_ROLE";
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                $scope.info.roleList = result.data.FEATURE_ROLE;
                $scope.selectRoleList = [];
            } else {
                $rootScope.showMessage("error", "失败", result.desc);
            }
        });
    };

    //单选按钮切换
    $scope.radioChange = function() {
        $scope.info.radioStatus == "true" ? "" : getFeatureList();
    };

    //获取功能点集列表
    function getFeatureList() {
        var url = matrix_product_url + "/feature/getFeature?sys=" + sysName + "&withPrototype=0";
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                console.log("getFeatureList");
                console.log(result.data);
                $scope.info.featureList = result.data;
            } else {
                $rootScope.showMessage("error", "失败", result.desc);
            }
        });
    };

    //校验form
    function vertifyForm() {
        if($scope.feature.name == ""){
            $(".form-name").children("input").addClass("required-error");
            $scope.info.createBtnStatus = false;
            return;
        } else {
            $(".form-name").children("input").addClass("required-success");
            $scope.info.createBtnStatus = true;
        }
    };

    //点击新增按钮
    $scope.createClick = function() {
        if($scope.info.radioStatus == "true") {
            vertifyForm();
        } else {
            if($scope.info.selectValue == "") {
                $(".form-select").children("select").addClass("required-error");
                $scope.info.createBtnStatus = false;
            } else {
                $(".form-select").children("select").addClass("required-success");
                $scope.info.createBtnStatus = true;
            }
        }
        if(!$scope.info.createBtnStatus) {
            $rootScope.showMessage("warning", "警告", "必填数据不能为空！");
            return false;
        }
        var featureData = $scope.info.radioStatus == "true" ? $scope.feature : $scope.info.selectValue;
        $scope.feature.role = $scope.info.selectRoleList;
        featureData.radioStatus = $scope.info.radioStatus;
        $modalInstance.close(featureData);
    };

    //点击取消按钮
    $scope.cancelClick = function() {
        $modalInstance.dismiss("cancel");
    };
}]);

app.controller("addFlowCtrl", ["$scope", "$rootScope", "$modalInstance", "$http", "branch", "sysName", "reqId", function($scope, $rootScope, $modalInstance, $http, branch, sysName, reqId) {
    $scope.featureList = [];
    $scope.flow = {
        name   : "",
        path   : "",
        pathId : "",
        desc   : "",
        feature: {}
    };

    getFeatureList();

    function getFeatureList() {
        $rootScope.showPanelLoading();
        var url = matrix_product_url +"/feature/getFeature?withAttr=0";
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                if(result.data) {
                    $scope.featureList = result.data;
                } else {
                    $rootScope.toasterErrorInfo("获取feature数据失败！");
                }
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
            $rootScope.hidePanelLoading();
        });
    };

    $scope.createClick = function() {
        var currentFeature = JSON.parse($scope.flow.feature);
        $scope.flow.path   = currentFeature.path;
        $scope.flow.pathId = currentFeature.id;
        delete $scope.flow.feature;
        $modalInstance.close($scope.flow);
    };

    $scope.cancelClick = function() {
        $modalInstance.dismiss("cancel");
    };
}]);